//
//  BKScanCardViewController.m
//  bestkeep
//
//  Created by yons on 16/11/24.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKScanCardViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <Masonry.h>
#import "Mediator+BKGD.h"

#define IPHONE_HEIGHT CGRectGetHeight([UIScreen mainScreen].bounds)
#define IPHONE_WIDTH [UIScreen mainScreen].bounds.size.width
//Get the OS version.       判断操作系统版本
#define IOS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
@interface BKScanCardViewController ()<AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate>
//捕捉流管理
@property(nonatomic,strong)AVCaptureSession *captureSession;
//输入捕捉绘画
@property(nonatomic,strong)AVCaptureDeviceInput *input;
//处理输出捕捉会话
@property(nonatomic,strong)AVCaptureMetadataOutput *output;
//相机输出流
@property(nonatomic,strong)AVCaptureVideoPreviewLayer *captureVideoPreviewLayer;
//信息
@property(nonatomic,strong)AVMetadataMachineReadableCodeObject *object;

//正方扫描框
@property(nonatomic,strong)UIView *sweepView;
//标题
@property(nonatomic,strong)UILabel *titleLabel;
//交互线
@property(nonatomic,strong)UIImageView *lineView;

@property(nonatomic,strong)CAShapeLayer *shapeLayer;

@property(nonatomic,assign)BOOL isReady;

@property(nonatomic,strong)NSTimer *timer;

@property(nonatomic,strong)UIView *borderView;

@end

@implementation BKScanCardViewController


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.automaticallyAdjustsScrollViewInsets = YES;
    if (_isReady) {
        [self startReading];
    }else{
        [self alertViewWithMessage:@"请打开摄像头" title:@"友情提示" object:nil];
    }
}

-(void)viewDidDisappear:(BOOL)animated{
    //用Device创建输入流  捕捉完结内容 到设备中 也就是手机
    AVCaptureDevice * Device = [AVCaptureDevice defaultDeviceWithMediaType: AVMediaTypeVideo];
    if ([Device hasTorch]) {
        
        [Device lockForConfiguration:nil];
        [Device setTorchMode:AVCaptureTorchModeOff];
        [Device unlockForConfiguration];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"扫一扫";
    self.view.backgroundColor = [UIColor whiteColor];
    self.sweepView.alpha = 1;
    self.sweepView.backgroundColor = [UIColor clearColor];
    if ([self didprepared]) {
        _isReady = YES;
    self.titleLabel.text = @"请扫描跨境淘商品标签上的二维码";
        [self.view.layer addSublayer:self.shapeLayer];
        [self.sweepView addSubview:self.lineView];
        self.view.layer.masksToBounds = YES;
    }
    
}

-(AVCaptureSession *)captureSession{
    if (!_captureSession) {
        _captureSession = [[AVCaptureSession alloc]init];
        [_captureSession setSessionPreset:AVCaptureSessionPreset1920x1080];
    }
    return _captureSession;
}

-(AVCaptureDeviceInput *)input{
    if (!_input) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        _input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    }
    return _input;
}

-(AVCaptureMetadataOutput *)output{
    if (!_output) {
        _output = [[AVCaptureMetadataOutput alloc]init];
        [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        _output.rectOfInterest = [self getRectOfInterestWithFrame:CGRectMake(IPHONE_WIDTH/6, IPHONE_HEIGHT/4, IPHONE_WIDTH/3*2, IPHONE_WIDTH/3*2)];
    }
    return _output;
}

-(UIView *)sweepView{
    if (!_sweepView) {
        _sweepView = [[UIView alloc]init];
        _sweepView.frame = CGRectMake(IPHONE_WIDTH/6, IPHONE_HEIGHT/4, IPHONE_WIDTH/3*2, IPHONE_WIDTH/3*2);
        _sweepView.clipsToBounds = YES;
        [self.view addSubview:_sweepView];
    }
    return _sweepView;
}
-(UIView *)borderView{
    if (!_borderView) {
        _borderView = [[UIView alloc]initWithFrame:self.sweepView.frame];
        _borderView.layer.borderColor = RGBACOLOR(0, 186, 156, 1).CGColor;
        _borderView.layer.borderWidth = .5f;
        UIView *borderView11 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 2.5f, 16)];
         UIView *borderView12 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 2.5f)];
        UIView *borderView21 = [[UIView alloc] initWithFrame:CGRectMake(self.sweepView.frame.size.width-16, 0, 16, 2.5f)];
        UIView *borderView22 = [[UIView alloc] initWithFrame:CGRectMake(self.sweepView.frame.size.width-2.5f, 0, 2.5f, 16)];
        UIView *borderView31 = [[UIView alloc] initWithFrame:CGRectMake(0, self.sweepView.frame.size.height-2.5f, 16, 2.5f)];
        UIView *borderView32 = [[UIView alloc] initWithFrame:CGRectMake(0, self.sweepView.frame.size.height-16, 2.5f, 16)];
        UIView *borderView41 = [[UIView alloc] initWithFrame:CGRectMake(self.sweepView.frame.size.width-2.5f, self.sweepView.frame.size.height-16, 2.5f, 16)];
        UIView *borderView42 = [[UIView alloc] initWithFrame:CGRectMake(self.sweepView.frame.size.width-16, self.sweepView.frame.size.height-2.5f, 16, 2.5f)];
        borderView11.backgroundColor = RGBACOLOR(0, 186, 156, 1);
        borderView12.backgroundColor = RGBACOLOR(0, 186, 156, 1);
        borderView21.backgroundColor = RGBACOLOR(0, 186, 156, 1);
        borderView22.backgroundColor = RGBACOLOR(0, 186, 156, 1);
        borderView31.backgroundColor = RGBACOLOR(0, 186, 156, 1);
        borderView32.backgroundColor = RGBACOLOR(0, 186, 156, 1);
        borderView41.backgroundColor = RGBACOLOR(0, 186, 156, 1);
        borderView42.backgroundColor = RGBACOLOR(0, 186, 156, 1);
        [_borderView addSubview:borderView11];
        [_borderView addSubview:borderView12];
        [_borderView addSubview:borderView21];
        [_borderView addSubview:borderView22];
        [_borderView addSubview:borderView31];
        [_borderView addSubview:borderView32];
        [_borderView addSubview:borderView41];
        [_borderView addSubview:borderView42];
        
    }
    return _borderView;
}

-(CAShapeLayer *)shapeLayer{
    if (!_shapeLayer) {
        _shapeLayer = [CAShapeLayer layer];
        _shapeLayer.path = [UIBezierPath bezierPathWithRect:[UIScreen mainScreen].bounds].CGPath;
        _shapeLayer.fillColor = [UIColor blackColor].CGColor;
        _shapeLayer.opacity = 0.3;
        _shapeLayer.mask = [self generateMaskLayerWithRect:[UIScreen mainScreen].bounds exceptRect:self.sweepView.frame];
    }
    return _shapeLayer;
}

-(AVCaptureVideoPreviewLayer *)captureVideoPreviewLayer{
    if (!_captureVideoPreviewLayer) {
        _captureVideoPreviewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
        [_captureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
        _captureVideoPreviewLayer.frame = self.view.frame;
        
    }
    return _captureVideoPreviewLayer;
}
-(UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.textColor = [UIColor whiteColor];
        [_titleLabel setTextAlignment:NSTextAlignmentCenter];
        _titleLabel.font = [Common systemFontOfSize:14];
        [self.view addSubview:_titleLabel];
        [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.sweepView.mas_centerX);
            make.top.mas_equalTo(self.sweepView.mas_bottom).mas_offset(10);
            make.width.mas_equalTo(self.sweepView.mas_width);
            make.height.mas_equalTo(@20);
        }];
    }
    return _titleLabel;
}
-(UIImageView *)lineView{
    if (!_lineView) {
        _lineView = [[UIImageView alloc]init];
        _lineView.frame = CGRectMake(0, -30, IPHONE_WIDTH/3*2, 30);
        _lineView.image = [UIImage imageNamed:@"BKScan_Sweep"];
        _lineView.contentMode = UIViewContentModeScaleAspectFit;
        
    }
    return _lineView;
}

-(NSTimer *)timer{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.9f target:self selector:@selector(moveScanLayer) userInfo:nil repeats:YES];
    }
    return _timer;
}

-(void)moveScanLayer{
     __block CGRect frame = self.lineView.frame;
    frame.origin.y = self.sweepView.bounds.origin.y-25;
    self.lineView.frame = frame;
    
    [UIView animateWithDuration:1.9f delay:0.0f options:UIViewAnimationOptionCurveEaseInOut animations:^{
        frame.origin.y += self.sweepView.frame.size.height+25;
        self.lineView.frame = frame;
    } completion:^(BOOL finished) {
    }];
}

//生成rectOfInterest
- (CGRect)getRectOfInterestWithFrame:(CGRect)frame {
    
    //扫描范围与选择像素有关，通过像素计算是扫描范围确定到框内；
    CGFloat scale1 = IPHONE_HEIGHT/IPHONE_WIDTH;
    CGFloat scale2 = 1920.0f/1080.0f;
    NSLog(@"%f,------%f",scale1,scale2);
    if (scale1 < scale2) {
        CGFloat fixHeight = IPHONE_WIDTH*1920.0f/1080.0f;
        CGFloat fixPadding = (fixHeight - IPHONE_HEIGHT)/2.0f;
        return CGRectMake((frame.origin.y + fixPadding)/fixHeight, frame.origin.x/IPHONE_WIDTH, frame.size.height/fixHeight, frame.size.width/IPHONE_WIDTH);
    }
    CGFloat fixWidth = IPHONE_HEIGHT*1080.0f/1920.0f;
    CGFloat fixPadding = (fixWidth - IPHONE_WIDTH)/2.0f;
    return CGRectMake(frame.origin.y/IPHONE_HEIGHT, (frame.origin.x + fixPadding)/fixWidth, frame.size.height/IPHONE_HEIGHT, frame.size.width/fixWidth);
}



//生成空缺layer 层；
- (CAShapeLayer *)generateMaskLayerWithRect: (CGRect)rect exceptRect: (CGRect)exceptRect {
    
    CAShapeLayer * maskLayer = [CAShapeLayer layer];
    if (!CGRectContainsRect(rect, exceptRect)) {
        
        return nil;
    }
    else if (CGRectEqualToRect(exceptRect, CGRectZero)) {
        maskLayer.path = [UIBezierPath bezierPathWithRect: rect].CGPath;
        return maskLayer;
    }
    
    CGFloat boundsInitX = CGRectGetMinX(rect);
    CGFloat boundsInitY = CGRectGetMinY(rect);
    CGFloat boundsWidth = CGRectGetWidth(rect);
    CGFloat boundsHeight = CGRectGetHeight(rect);
    
    CGFloat minX = CGRectGetMinX(exceptRect);
    CGFloat maxX = CGRectGetMaxX(exceptRect);
    CGFloat minY = CGRectGetMinY(exceptRect);
    CGFloat maxY = CGRectGetMaxY(exceptRect);
    CGFloat width = CGRectGetWidth(exceptRect);
    
    /** 添加路径*/
    UIBezierPath * path = [UIBezierPath bezierPathWithRect: CGRectMake(boundsInitX, boundsInitY, minX, boundsHeight)];
    [path appendPath: [UIBezierPath bezierPathWithRect: CGRectMake(minX, boundsInitY, width, minY)]];
    [path appendPath: [UIBezierPath bezierPathWithRect: CGRectMake(maxX, boundsInitY, boundsWidth - maxX, boundsHeight)]];
    [path appendPath: [UIBezierPath bezierPathWithRect: CGRectMake(minX, maxY, width, boundsHeight - maxY)]];
    maskLayer.path = path.CGPath;
    
    return maskLayer;
}

-(BOOL)didprepared{
    [self.view.layer insertSublayer:self.captureVideoPreviewLayer atIndex:0];
    [self.view addSubview:self.borderView];
    [self.captureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    if ([self.captureSession canAddInput:self.input]) {
        [_captureSession addInput:_input];
        if ([self.captureSession canAddOutput:self.output]) {
            [_captureSession addOutput:_output];
            _output.metadataObjectTypes = @[AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeQRCode];
            [self.view.layer insertSublayer:self.captureVideoPreviewLayer atIndex:0];
            [self.captureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
            return YES;
        }else{
            return NO;
        }
    }else{
        return NO;
    }
}

- (void)startReading{
    [self.captureSession startRunning];
    [self.timer setFireDate:[NSDate distantPast]];
}

-(void)stopReading{
    [self.captureSession stopRunning];
    [self.timer setFireDate:[NSDate distantFuture]];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    //处理捕捉到的内容
    if ([metadataObjects count]>0&&metadataObjects !=nil) {
        AVMetadataMachineReadableCodeObject *object = [metadataObjects objectAtIndex:0];
        if ([[object type] isEqualToString:AVMetadataObjectTypeQRCode] |  [[object type] isEqualToString:AVMetadataObjectTypeEAN13Code]) {
            _object = object;
            NSString *urlStr = [object stringValue];
            
            [self getGoodsNumberFromURL:urlStr];
        }
    }
}

/**
 传人商品的链接，传出商品的ID；
 
 @param UrlStr 商品的链接 例：http://www.bestkeep.cn/item/15751580
 
  商品的ID   http:www.bestkeep.cn/item/34392644?bsh_bid=1550372742&bsh_vuid=939724
 */
- (void)getGoodsNumberFromURL:(NSString *)UrlStr {
    
    if ([UrlStr rangeOfString:@"bestkeep.cn/item/"].location != NSNotFound) {
        NSMutableString *mutUrlStr = [UrlStr mutableCopy];
        if ([UrlStr rangeOfString:@"?"].location != NSNotFound) {
            
            [self stopReading];
            NSRange rangeEnd = [mutUrlStr rangeOfString:@"?"];
            NSRange rangeStart = [mutUrlStr rangeOfString:@".bestkeep.cn/item/"];
            //获取参数 临时字符串
            NSMutableString *tempMutStr = [UrlStr mutableCopy];
            
            mutUrlStr = [[mutUrlStr substringToIndex:rangeEnd.location] mutableCopy];
            rangeStart.length = rangeStart.location + rangeStart.length;
            rangeStart.location = 0;
            [mutUrlStr deleteCharactersInRange:rangeStart];
            
            tempMutStr = [[tempMutStr substringFromIndex:rangeEnd.location+1] mutableCopy];
            NSLog(@"====================%@",tempMutStr);
            
            NSMutableDictionary *dic = [self handleStringParameterWithMutStr:tempMutStr];
            
            UIViewController *detailVC;
            if (dic.allKeys.count) {
                detailVC = [[Mediator sharedInstance] BKGD_goodsDetailViewController:mutUrlStr saleTypes:dic[@"saleTypes"] storeId:dic[@"storeId"] shopKeeper:dic[@"shopKeeper"]];
            }else {
                detailVC = [[Mediator sharedInstance] BKGD_goodsDetailViewController:mutUrlStr saleTypes:nil];
            }
            [self.navigationController pushViewController:detailVC animated:YES];
            
        }else {
            
            NSRange range = [mutUrlStr rangeOfString:@".bestkeep.cn/item/"];
            
            range.length = range.location + range.length;
            range.location = 0;
            
            [mutUrlStr deleteCharactersInRange:range];
            UIViewController *detailVC = [[Mediator sharedInstance] BKGD_goodsDetailViewController:mutUrlStr saleTypes:nil];
            [self.navigationController pushViewController:detailVC animated:YES];
            [self stopReading];
        }
    }else if ([UrlStr hasPrefix:@"http"]){
        [self stopReading];
        [self alertViewWithMessage:UrlStr title:@"可能存在风险，是否打开" object:_object];
    }else {
        [self stopReading];
        [self alertViewWithMessage:UrlStr title:@"提示" object:_object];
    }
}

- (void)alertViewWithMessage:(NSString *)message title:(NSString *)title object:(AVMetadataMachineReadableCodeObject *)object{
    
    if (IOS_VERSION < 8.0f) {
        
        UIAlertView * alart = [[UIAlertView alloc]initWithTitle:title message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        _object = object;
        [alart show];
    }else {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            if ([message isEqualToString:@"请打开摄像头"]) {
                
                [self.navigationController popViewControllerAnimated:YES];
            }else {
                [self startReading];
            }
        }];
        
        UIAlertAction *alertOpenAction = [UIAlertAction actionWithTitle:@"打开" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            if ([message isEqualToString:@"请打开摄像头"]) {
                
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL:url];
                    
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }else if ([title isEqualToString:@"可能存在风险，是否打开"]) {
                
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:object.stringValue]];
                [self.navigationController popViewControllerAnimated:YES];
            }else {
                [self startReading];
            }
        }];
        
        [alertC addAction:alertAction];
        [alertC addAction:alertOpenAction];
        [self presentViewController:alertC animated:YES completion:nil];
    }
}

- (NSMutableDictionary *)handleStringParameterWithMutStr:(NSMutableString *)parameterMutStr {
    //http://www.bestkeep.cn/item/MhZY_D83TIO7fRzxjglxjA?storeId=1234321&shopKeeper=1122334455&saleTypes=3
    
    NSMutableDictionary *parameterMutDic = [NSMutableDictionary dictionary];
    parameterMutStr = [[parameterMutStr stringByReplacingOccurrencesOfString:@" " withString:@""] mutableCopy];
    for (NSString *tempStr in [parameterMutStr componentsSeparatedByString:@"&"]) {
        NSLog(@"+++++++%@",tempStr);
        
        NSMutableString *tempMutStr = [tempStr mutableCopy];
        
        if (([tempStr rangeOfString:@"storeId="].location != NSNotFound)) {
            NSRange rangeEnd = [tempStr rangeOfString:@"storeId="];
            
            tempMutStr = [[tempStr substringFromIndex:rangeEnd.location+rangeEnd.length] mutableCopy];
            
            [parameterMutDic setValue:tempMutStr forKey:@"storeId"];
        }
        if (([tempStr rangeOfString:@"shopKeeper="].location != NSNotFound)) {
            NSRange rangeEnd = [tempStr rangeOfString:@"shopKeeper="];
            
            tempMutStr = [[tempStr substringFromIndex:rangeEnd.location+rangeEnd.length] mutableCopy];
            
            [parameterMutDic setValue:tempMutStr forKey:@"shopKeeper"];
        }
        if (([tempStr rangeOfString:@"saleTypes="].location != NSNotFound)) {
            NSRange rangeEnd = [tempStr rangeOfString:@"saleTypes="];
            
            tempMutStr = [[tempStr substringFromIndex:rangeEnd.location+rangeEnd.length] mutableCopy];
            
            [parameterMutDic setValue:tempMutStr forKey:@"saleTypes"];
        }
    }
    NSLog(@"%@",parameterMutDic);
    return parameterMutDic;
}


























- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
